package org.linlinjava.litemall.wx.task;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.system.SystemConfig;
import org.linlinjava.litemall.core.task.Task;
import org.linlinjava.litemall.core.util.BeanUtil;
import org.linlinjava.litemall.db.domain.LitemallGroupon;
import org.linlinjava.litemall.db.domain.LitemallOrder;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.GrouponConstant;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.linlinjava.litemall.wx.service.WxOrderService;

import java.time.LocalDateTime;
import java.util.List;

public class GrouponUnpaidTask extends Task {
    private final Log logger = LogFactory.getLog(GrouponUnpaidTask.class);
    private int grouponId = -1;

    public GrouponUnpaidTask(Integer grouponId, long delayInMilliseconds){
        super("GrouponUnpaidTask-" + grouponId, delayInMilliseconds);
        this.grouponId = grouponId;
    }

    public GrouponUnpaidTask(Integer grouponId) {
        super("GrouponUnpaidTask-" + grouponId, SystemConfig.getGrouponUnpaid() * 60 * 1000);
        this.grouponId = grouponId;
    }

    @Override
    public void run() {
        logger.info("系统开始处理延时任务---团购超时---" + this.grouponId);

        LitemallGrouponService grouponService = BeanUtil.getBean(LitemallGrouponService.class);

        LitemallGroupon groupon = grouponService.findById(this.grouponId);
        if(groupon == null){
            return;
        }
        if (groupon.getStatus().equals(GrouponConstant.STATUS_SUCCEED)) {
            return;
        }
        if(!groupon.getGrouponId().equals(0)) { // 不是发起者
            return;
        }
        end(groupon, grouponService);
        List<LitemallGroupon> involvers = grouponService.queryJoinRecord(groupon.getId()); // 参与者
        for (LitemallGroupon involver:involvers) {
            end(involver, grouponService);
        }
        logger.info("系统结束处理延时任务---团购超时---" + this.grouponId);
    }

    private void end(LitemallGroupon groupon, LitemallGrouponService grouponService) {
        LitemallOrderService orderService = BeanUtil.getBean(LitemallOrderService.class);
        WxOrderService wxOrderService = BeanUtil.getBean(WxOrderService.class);
        groupon.setStatus(GrouponConstant.STATUS_EXPIRE); // 超时
        grouponService.updateById(groupon);
        Integer orderId = groupon.getOrderId();
        LitemallOrder order = orderService.findById(orderId);
        if (order.getOrderStatus().equals(OrderUtil.STATUS_PAY)) {
            wxOrderService.doRefund(order);
        }
    }
}
